import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import '../css3/Exchange.scss'
import { Button, Image } from 'react-vant'
import { Phone, Photograph, Volume } from '@react-vant/icons'
import { io } from "socket.io-client";
import {
    LocalUser,
    RemoteUser,
    useIsConnected,
    useJoin,
    useLocalMicrophoneTrack,
    useLocalCameraTrack,
    usePublish,
    useRemoteUsers,
} from "agora-rtc-react";

function Exchange() {
    const navigate = useNavigate()
    const { state } = useLocation()
    const [answer, setAnswer] = useState(false)
    const [calling, setCalling] = useState(false)   // 是否在呼叫
    const isConnected = useIsConnected()   // 存储用户的连接状态
    const [messages, setMessages] = useState({
        appId: "eeaea820dab04ca497e18788de1e572f",   // 存储 App ID的状态
        channel: "video",   // 存储频道名的状态
        token: "007eJxTYEj3ySlo/sE7ZVW0yY+XzFGa65vbb0gwC4a8dWNcKdYZx67AkJqamJpoYWSQkphkYJKcaGJpnmpoYW5hkZJqmGpqbpT2+mp/WkMgI8PCWasYGKEQxGdlKMtMSc1nYAAA/8MfMg==",   // 存储Token 的状态
    })
    // 监听是否呼叫成功
    useJoin({ appid: messages.appId, channel: messages.channel, token: messages.token }, calling)
    const [micOn, setMic] = useState(false)   // 是否打开麦克风
    const [cameraOn, setCamera] = useState(false)   // 是否打开摄像头
    const { localMicrophoneTrack } = useLocalMicrophoneTrack(micOn);   // 监听麦克风状态
    const { localCameraTrack } = useLocalCameraTrack(cameraOn);   // 监听摄像头状态
    usePublish([localMicrophoneTrack, localCameraTrack]);    // 发布本地音视频流
    // 远端用户接收
    const remoteUsers = useRemoteUsers()   // 存储远端用户的状态

    const user = JSON.parse(sessionStorage.getItem('user'))
    const friend = JSON.parse(sessionStorage.getItem('friend'))


    const socket = io('http://localhost:3000', {
        query: { userId: user._id, },
        extraHeaders: { "Access-Control-Allow-Origin": "*" }
    })

    const sendMessage = (type) => {
        switch (type) {
            case "break":
                socket.emit('send', {
                    type: 'break',
                })
                break
            case "succeed":
                socket.emit('send', {
                    type: 'succeed',
                })
                break
        }
    }

    socket.on('receive', (data) => {
        switch (data.type) {
            case "break":
                setCalling(false)
                navigate('/dialogue')
                navigate(0)
                break
            case "succeed":
                setCalling(true)
                break
        }
    })


    const button = useMemo(() => {
        return < >
            <div className="btn">
                <Button
                    type={cameraOn ? 'primary' : 'default'}
                    icon={<Photograph />}
                    round
                    onClick={() => setCamera(a => !a)}
                />
                <Button
                    type={micOn ? 'primary' : 'default'}
                    icon={<Volume />}
                    round
                    onClick={() => setMic(a => !a)}
                />
            </div>
            <Button
                size='large'
                type='danger'
                round
                onClick={() => sendMessage('break')}
            >挂断</Button>
        </>
    })

    return (
        <div id='exchange'>
            <div id="box" >
                {
                    isConnected ? (
                        <div id='video'>
                            <div className='video' id='local-user'>
                                <LocalUser
                                    audioTrack={localMicrophoneTrack}
                                    cameraOn={cameraOn}
                                    micOn={micOn}
                                    videoTrack={localCameraTrack}
                                    cover="https://www.agora.io/en/wp-content/uploads/2022/10/3d-spatial-audio-icon.svg"
                                />

                            </div>
                            {
                                remoteUsers.map(user => (
                                    <div key={user.uid} className='video' id='remote-user'>
                                        <RemoteUser
                                            cover="https://www.agora.io/en/wp-content/uploads/2022/10/3d-spatial-audio-icon.svg"
                                            user={user}
                                        />
                                    </div>
                                ))
                            }


                        </div>
                    ) : (
                        <div id="info">
                            <h3>{state.title}</h3>
                            <h1></h1>
                            <div id="user1">
                                <div id="user2">
                                    <Image width={80} height={80} round src={friend.picture} />
                                </div>
                            </div>
                        </div>
                    )
                }
            </div>

            <div id="bottom">
                {
                    state.type === 'dial' ? (<>{button}</>) : (
                        <>
                            {
                                answer ? (<>{button}</>) :
                                    <div className='btn'>
                                        <Button
                                            type='danger'
                                            round
                                            onClick={() => sendMessage('break')}
                                            icon={<Phone rotate={135} />}
                                        />
                                        <Button
                                            type='info'
                                            round
                                            onClick={() => {
                                                setAnswer(true)
                                                setCalling(true)
                                                sendMessage('succeed')
                                            }}
                                            icon={<Phone />}
                                        />
                                    </div>
                            }
                        </>
                    )
                }


            </div >
        </div >
    )
}

export default Exchange